package com.itelite.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itelite.common.util.JwtTokenUtils;
import com.itelite.domain.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/5/13-15:21
 **/
@Component
@Slf4j
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    //登录成功后调用
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //根据配置中来选择是执行跳转,还是返回字符串
        response.setContentType("application/json;charset=UTF-8");
        //登陆成功，返回认证信息
        User user = (User) authentication.getPrincipal();
        Map<String,Object> map = Map.of("userId",user.getUserId(),"authorities",user.getAuthorities());
        JwtTokenUtils.createJwt(user,request.getParameter("rememberMe")==null? 0:1,response);
    }
}
